import { _decorator, Component, Node } from 'cc'
import { TileMapManager } from '../Tile/TileMapManager'
import { CreateUINode } from '../../Utils'
import  Levels, { Ilevel } from '../../Levels'
import { TILE_WIDTH } from '../Tile/TileManager'
import DataManager from '../../Runtime/DataManager'
import EventManager from '../../Runtime/EventManager'
import { EVENT_ENUM } from '../../Enums'
import { PlayerManager } from '../Player/PlayerManager'

const { ccclass, property } = _decorator


@ccclass('BattleManager')
export class BattleManager extends Component {
    level:Ilevel
    stage:Node
    start(){
        this.generateStage()
        this.initLevel()
    }
    //绑定事件周期函数
    onLoad(){
        EventManager.Instance.on(EVENT_ENUM.NEXT_LEVEL,this.nextLevel,this)
    }
    //解绑事件周期函数
    onDestroy(){
        EventManager.Instance.off(EVENT_ENUM.NEXT_LEVEL,this.nextLevel)
    }
    //初始化关卡
    initLevel(){
    const level =Levels[`Level${DataManager.Instance.leveIndex}`]
    if(level){
        this.clearLastLevel()

        this.level =level

        DataManager.Instance.mapInfo = this.level.mapInfo
        DataManager.Instance.mapRowCount = this.level.mapInfo.length || 0
        DataManager.Instance.mapColumnCount = this.level.mapInfo[0].length || 0

        this.generateTileMap()
        this.generatePlayer()
        }
        else{
            console.error('没有找到关卡数据')
        }
    }
    //生成玩家
    generatePlayer() {
        const player = CreateUINode()
        player.setParent(this.stage)
        const playerManager = player.addComponent(PlayerManager)
        playerManager.init()
    }
    //生成舞台
    generateStage(){
       this.stage =CreateUINode()
       this.stage.setParent(this.node)

    }
    //下一关地图
    nextLevel(){
        DataManager.Instance.leveIndex++
        this.initLevel()
        console.log('下一关')
    }
    //清空上一关地图
    clearLastLevel(){
        this.stage.destroyAllChildren()
        DataManager.Instance.reset()
    }

    //生成地图
    generateTileMap() {

       const tileMap =CreateUINode()
       tileMap.setParent(this.stage)
       const tileMapManager = tileMap.addComponent(TileMapManager)
       tileMapManager.init()
       //适配屏幕位置
       this.adaptPos()
    }
    //适配屏幕位置
    adaptPos() {
        const { mapRowCount, mapColumnCount } = DataManager.Instance
        const disX = (TILE_WIDTH  * mapRowCount) /2
        const disY = (TILE_WIDTH  * mapColumnCount)/2 + 80
        this.stage.setPosition(-disX,disY)

    }
}



